const contextPath = window.contextPath

const mergeQuery = (url, query, noContext) => {
  if(url.substr(0,7).toLowerCase() != "http://" && url.substr(0,8).toLowerCase() != "https://") {
     let urlIndex = url.indexOf(contextPath);
    if(urlIndex === 0 || urlIndex === 1) {
      url = urlIndex === 0 ? url : '/' + url;
    } else {
      if(!noContext){
        url = contextPath + url
      }
    }
  }

  if (!query) {
    return url
  }

  let params = []
  for(let key in query) {
    const value = query[key]
    if (value === undefined) {
      continue
    }
    params.push(`${key}=${encodeURIComponent(query[key])}`)
  }

  url = url + '?' + params.join('&');

  return url
}

export const request = (url, {
  method='GET',
  query,
  data,
  headers={},
  noContext=false
} = {}) => {
  const req = new Request(mergeQuery(url, query, noContext), {
    method,
    body: data,
    headers: headers,
    mode: 'cors',
    credentials: 'include',
  })
  return fetch(req).then(res => res.json()).then(res => {
    // if(res && res.code !== "0") {
    //   console.error('request failed', res)
    //   throw new Error(`error code: ${res.code}`)
    // }
    return res
  }).catch(err => {
    console.error('Caught error: ', err)
  })
}
